# 罗马数字包含七种字符：
# | I | V |  X |  L |   C |   D |    M |
# | 1 | 5 | 10 | 50 | 100 | 500 | 1000 |
# 特例，I放在V和X左边，表示4和9
# X放在L和C左边，表示40和90
# C放在D和M左边，表示400和900
# 给定一个罗马数字，范围在1到3999，将其转换成整数。

n1 = "III"
n2 = "IV"
n3 = "IX"
n4 = "LVIII"
n5 = "MCMXCIV"

# 建立dict存储罗马数字的整数值，无须多次if判断数值是否相等，
# 每次循环，n[i]即字符串n中的字符，对应dicts中的key；则dicts[n[i]]即为value

def roman_numbers_to_int(n):
    dicts = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1}
    total = 0
    for i in range(len(n) - 1):
        if dicts[n[i]] < dicts[n[i + 1]]:
            total -= dicts[n[i]]
        else:
            total += dicts[n[i]]
    total += dicts[n[-1]]
    return(total)

print(roman_numbers_to_int(n1))
print(roman_numbers_to_int(n2))
print(roman_numbers_to_int(n3))
print(roman_numbers_to_int(n4))
print(roman_numbers_to_int(n5))

# # 此函数仅对n5生效，n[i-1]或n[i+1]均可有特殊情况
# def roman_number(n):
#     total = 0
#     for i in range(len(n)):
#         if n[i] == "M":
#             if n[i - 1] == "C":
#                 total -= 100
#             total += 1000
#         elif n[i] == "D":
#             if n[i - 1] == "C":
#                 total -= 100
#             total += 500
#         elif n[i] == "C":
#             if n[i + 1] == "M" or n[i + 1] == "D":
#                 continue
#             elif n[i - 1] == "X":
#                 total -= 10
#             total += 100
#         elif n[i] == "L":
#             if n[i - 1] == "X":
#                 total -= 10
#             total += 50
#         elif n[i] == "X":
#             if n[i + 1] == ("C" or "L"):
#                 continue
#             elif n[i - 1] == "I":
#                 total -= 1
#             total += 10
#         elif n[i] == "V":
#             if n[i - 1] == "I":
#                 total -= 1
#             total += 5
#         elif n[i] == "I":
#             if n[i + 1] == ("V" or "X"):
#                 continue
#             else:
#                 total += 1
#         else:
#             continue
#         print(total)
#     return total
